package com.nf.health.app.activity.my.pay;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.bean.CreateOrderBean;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.Apis;
import com.nf.health.app.impl.event.EventType;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.MathUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.utils.pay.PayResult;
import com.nf.health.app.utils.wximpl.bean.OrederSendInfo;
import com.nf.health.app.utils.wximpl.utils.WXpayUtils;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/5/8/008.
 * 扫码支付
 */

public class MyScannerPayActivity extends BaseActivity {
    //    @Bind(R.id.titlebar_right_tv)
//    TextView titlebarRightTv;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.et_healthicon)//输入兑换健康币
            EditText ethealthicon;
    @Bind(R.id.alipay_check)
    CheckBox alipayCheck;
    @Bind(R.id.btn_binding)
    Button btnBinding;
    @Bind(R.id.keyonghealthicon)//以后健康币
            TextView keyonghealthicon;

    boolean yes = true;
    /*****************************************************************
     * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
     *****************************************************************/
    String mMode = "00";
    String icon;

    String sjmoney;

    /*支付宝支付结果码*/
    private static final String PAY_OK = "9000";// 支付成功
    private static final String PAY_WAIT_CONFIRM = "8000";// 交易待确认
    private static final String PAY_NET_ERR = "6002";// 网络出错
    private static final String PAY_CANCLE = "6001";// 交易取消
    private static final String PAY_FAILED = "4000";// 交易失败/*内部类，处理支付宝支付结果*/
    private static final int SDK_PAY_FLAG = 1;


    String type = "";
    String money;
    @Bind(R.id.yinlian_check)
    CheckBox yinlianCheck;
    @Bind(R.id.wchat_check)
    CheckBox wchatCheck;
    @Bind(R.id.ll_yinlian_check)
    LinearLayout ll_yinlian_check;
    @Bind(R.id.ll_wchat_check)
    LinearLayout ll_wchat_check;
    @Bind(R.id.ll_alipay_check)
    LinearLayout ll_alipay_check;
    @Bind(R.id.tv_sjmoney)
    TextView tvSjmoney;//还需支付
    @Bind(R.id.health_icon_keyong)
    TextView healthIconKeyong;

    private String URL = "";


    String healthMoney = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_my_scanner_pay);
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "支付");

        URL = getIntent().getStringExtra(Constants.PAY_URL);
        resisitListener();

        //请求将健康的个数
        provider.getUserHealthMoenyNUm();

        ethealthicon.setEnabled(false);

    }

    private void resisitListener() {
        btnBinding.setOnClickListener(this);
        alipayCheck.setOnClickListener(this);
        keyonghealthicon.setOnClickListener(this);
        yinlianCheck.setOnClickListener(this);
        wchatCheck.setOnClickListener(this);
        ll_yinlian_check.setOnClickListener(this);
        ll_wchat_check.setOnClickListener(this);
        ll_alipay_check.setOnClickListener(this);
        yinlianCheck.setOnCheckedChangeListener(null);
        alipayCheck.setOnCheckedChangeListener(null);
        wchatCheck.setOnCheckedChangeListener(null);
        EventBus.getDefault().register(this);
        setPricePoint(etMoney);
        setPricePoint(ethealthicon);


        ethealthicon.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(etMoney.getText().toString())) {
                    showToast("请先输入要支付的金额~");
                    return;
                }
                if (TextUtils.isEmpty(ethealthicon.getText().toString())) {
                    tvSjmoney.setText(etMoney.getText().toString());
                    return;
                }

                if (TextUtils.isEmpty(keyonghealthicon.getText().toString())) {
                    showToast("健康币不可用~");
                    return;
                }

                int a = new BigDecimal(keyonghealthicon.getText().toString()).multiply(new BigDecimal(100)).intValue();//健康比共有
                int b = new BigDecimal(s.toString()).multiply(new BigDecimal(100)).intValue();//输入健康比
                int c = new BigDecimal(etMoney.getText().toString()).multiply(new BigDecimal(100)).intValue();//支付金额
                if (b > a) {
                    if (s.length() > 1) {
                        s.delete(s.length() - 1, s.length());
                    } else {
                        s.delete(0, s.length());
                    }
                    showToast("不可以超出可用健康币数量");
                } else {
                    if (b > c) {
                        showToast("使用的健康币不可以超出支付金额");
                        if (s.length() > 1) {
                            s.delete(s.length() - 1, s.length());
                        } else {
                            s.delete(0, s.length());
                        }
                      /*  tvSjmoney.setText(etMoney.getText().toString());*/
                    } else {
                        tvSjmoney.setText((MathUtils.getFloats((c - b) * 0.01)));
                    }

                }
            }
        });
        etMoney.addTextChangedListener(new TextWatcher() {//上面
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(etMoney.getText())) {
                    ethealthicon.setEnabled(false);
                    tvSjmoney.setText("0");
                } else {
                    ethealthicon.setEnabled(true);
                    tvSjmoney.setText(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.keyonghealthicon:////网络不好 重新获取

                provider.getUserHealthMoenyNUm();

            case R.id.ll_alipay_check:////支付宝
                if (alipayCheck.isChecked()) {
                    type = "";
                    yinlianCheck.setChecked(false);
                    wchatCheck.setChecked(false);
                    alipayCheck.setChecked(false);
                } else {
                    yinlianCheck.setChecked(false);
                    wchatCheck.setChecked(false);
                    alipayCheck.setChecked(true);
                    type = "alipay";
                }
                break;
            case R.id.alipay_check://支付宝
                if (alipayCheck.isChecked()) {
                    type = "alipay";
                    yinlianCheck.setChecked(false);
                    wchatCheck.setChecked(false);
                    alipayCheck.setChecked(true);
                } else {
                    alipayCheck.setChecked(false);
                    type = "";
                }
                break;
            case R.id.ll_wchat_check://微信
                if (wchatCheck.isChecked()) {
                    type = "";
                    yinlianCheck.setChecked(false);
                    wchatCheck.setChecked(false);
                    alipayCheck.setChecked(false);
                } else {
                    yinlianCheck.setChecked(false);
                    wchatCheck.setChecked(true);
                    alipayCheck.setChecked(false);
                    type = "wchat";
                }
                break;
            case R.id.wchat_check://微信
                if (wchatCheck.isChecked()) {
                    type = "wchat";
                    yinlianCheck.setChecked(false);
                    alipayCheck.setChecked(false);
                    wchatCheck.setChecked(true);
                } else {
                    wchatCheck.setChecked(false);
                    type = "";
                }
                break;
            case R.id.ll_yinlian_check://银联
                if (yinlianCheck.isChecked()) {
                    type = "";
                    yinlianCheck.setChecked(false);
                    wchatCheck.setChecked(false);
                    alipayCheck.setChecked(false);
                } else {
                    yinlianCheck.setChecked(true);
                    wchatCheck.setChecked(false);
                    alipayCheck.setChecked(false);
                    type = "bank";
                }
            case R.id.yinlian_check://银联
                if (yinlianCheck.isChecked()) {
                    type = "bank";
                    alipayCheck.setChecked(false);
                    wchatCheck.setChecked(false);
                    yinlianCheck.setChecked(true);
                } else {
                    yinlianCheck.setChecked(false);
                    type = "";
                }
                break;
            case R.id.titlebar_right_tv://跳转到支付详情页面
                break;
            case R.id.btn_binding://支付

                sjmoney = tvSjmoney.getText().toString();//还需支付金额
                money = etMoney.getText().toString();
                icon = ethealthicon.getText().toString();
                if (TextUtils.isEmpty(icon)) {
                    icon = "0";
                }
                int coin = new BigDecimal(icon).multiply(new BigDecimal(100)).intValue();
                int price = new BigDecimal(money).multiply(new BigDecimal(100)).intValue();

                if (TextUtils.isEmpty(money)) {
                    showToast("请输入支付余额~");
                    break;
                } else if (Double.parseDouble(money) == 0) {
                    showToast("输入金额不能为0元~");
                    break;
                } else if (price > coin && !yinlianCheck.isChecked() && !wchatCheck.isChecked() && !alipayCheck.isChecked()) {
                    showToast("请选择支付方式~");
                    return;
                } else {
                    provider.getScanResultPayOrder(URL + "&healthycoin=" + coin + "&price=" + price);
                }

        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (Act.Flag.CREATE_MIND_ALIPAY_ORDER_FLAG.equals(actionName)) {//回调支付宝支付
            String signFlag = object.toString();
            if (!TextUtils.isEmpty(signFlag)) {
                payToOrderService(signFlag);
            }
        } else if (Act.Flag.FLAG_PAY_WEIXIN_PAT_ORSER.equals(actionName)) {//回调微信支付
            OrederSendInfo orederSendInfo = (OrederSendInfo) object;
            if (!TextUtils.isEmpty(orederSendInfo.getPrepay_id())) {
                WXpayUtils.Pay(orederSendInfo);
                // WXpayUtils.Pay(orederSendInfo.getPrepay_id());
            }
        } else if (Act.Flag.FLAG_UNION_PAY_ORDER.equals(actionName)) {
            CreateOrderBean bean = (CreateOrderBean) object;

            if (TextUtils.isEmpty(bean.getOrderno())) {
                showToast("订单号为空");
                return;
            }
            if (!bean.getSignFlag().equals("1")) {
                ActivityUtils.showActivity(MyScannerPayActivity.this, ScannerPaySuccessActivity.class);
                finish();
                showToast("支付成功");
                return;
            }
            if (yinlianCheck.isChecked()) {//当前选择的是银联
                provider.unionpaySign(bean.getOrderno());//回调银联支付
            } else if (wchatCheck.isChecked()) {//当前选择的是微信
                provider.payWeiXinOrder(bean.getOrderno());
            } else if (alipayCheck.isChecked()) {//当前选择的是支付宝
                provider.createMindAlipayOrder(bean.getOrderno());
            }
        } else if (Act.Flag.FLAG_UNIONPAY_SIGN.equals(actionName)) {//回调银联支付
            try {
                String tn = (String) object;
                if (Apis.HOST_COMMON.contains("test.")) {
                    mMode = "01";
                }
                UPPayAssistEx.startPay(this, null, null, tn, mMode);
            } catch (Exception e) {
                showToast("银联支付出错...");
                e.printStackTrace();
            }
        } else if (Act.Flag.FLAG_GET_USERHEALTH_MOENY_COUNT.equals(actionName)) {

            healthMoney = object.toString();
            if (!TextUtils.isEmpty(healthMoney)) {
                PreferenceHelper.putString(PreferenceHelper.HEALTH_MOENY, healthMoney);
                keyonghealthicon.setText(healthMoney);
                healthIconKeyong.setVisibility(View.VISIBLE);
                healthIconKeyong.setText("健康币可用");
                yes = false;
            }
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);

    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
        if (yes) {
            keyonghealthicon.setText("请点击重新获取");
            healthIconKeyong.setVisibility(View.GONE);
        }
    }

    /**
     * 支付宝进行请求
     *
     * @param signInfo
     */
    private void payToOrderService(final String signInfo) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                PayTask payTask = new PayTask(MyScannerPayActivity.this);
                // String result = payTask.pay(signInfo, true);
                Map<String, String> result = payTask.payV2(signInfo, true);
                Message message = mHandler.obtainMessage();
                message.what = SDK_PAY_FLAG;
                message.obj = result;
                mHandler.sendMessage(message);

            }
        }.start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = null;
                    try {
                        payResult = new PayResult((Map<String, String>) msg.obj);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, PAY_OK)) {//----------------------------------->支付成功
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(MyScannerPayActivity.this, "支付成功", Toast.LENGTH_LONG).show();
                        ActivityUtils.showActivity(MyScannerPayActivity.this, ScannerPaySuccessActivity.class);
                        finish();
                    } else if (TextUtils.equals(resultStatus, PAY_FAILED)) {//------------------------->支付失败
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(MyScannerPayActivity.this, "" + payResult.getMemo(), Toast.LENGTH_LONG).show();
                    } else if (TextUtils.equals(resultStatus, PAY_CANCLE)) {//-------------------------->交易取消
                        Toast.makeText(MyScannerPayActivity.this, "" + payResult.getMemo(), Toast.LENGTH_LONG).show();
                    } else if (TextUtils.equals(resultStatus, PAY_NET_ERR)) {//------------------------->网络出现错误
                        Toast.makeText(MyScannerPayActivity.this, "" + payResult.getMemo(), Toast.LENGTH_LONG).show();
                    } else if (TextUtils.equals(resultStatus, PAY_WAIT_CONFIRM)) {//--------------------->交替等待
                    }
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /*************************************************
         * 步骤3：处理银联手机支付控件返回的支付结果
         ************************************************/
        if (data == null) {
            return;
        }
        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {

            // 如果想对结果数据验签，可使用下面这段代码，但建议不验签，直接去商户后台查询交易结果
            // result_data结构见c）result_data参数说明
            if (data.hasExtra("result_data")) {
                String result = data.getExtras().getString("result_data");
                try {
                    JSONObject resultJson = new JSONObject(result);
                    String sign = resultJson.getString("sign");
                    String dataOrg = resultJson.getString("data");
                    // 此处的verify建议送去商户后台做验签
                    // 如要放在手机端验，则代码必须支持更新证书
                    boolean ret = verify(dataOrg, sign, mMode);
                    if (ret) {
                        // 验签成功，显示支付结果
                        msg = "支付成功！";
                    } else {
                        // 验签失败
                        msg = "支付失败！";
                    }
                } catch (JSONException e) {
                }
            }
            // 结果result_data为成功时，去商户后台查询一下再展示成功
            msg = "支付成功！";
            finish();
        } else if (str.equalsIgnoreCase("fail")) {
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "用户取消了支付";
        }

//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("支付结果通知");
//        builder.setMessage(msg);
//        builder.setInverseBackgroundForced(true);
//        // builder.setCustomTitle();
//        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        builder.create().show();
        showToast(msg);

    }

    private boolean verify(String msg, String sign64, String mode) {
        // 此处的verify，商户需送去商户后台做验签
        return true;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThreadUi(EventType eventType) {
        String type = eventType.getMsg();
        if (!TextUtils.isEmpty(type)) {
            if (Constants.PAY_WX_SUCCESS.equals(type)) {//微信支付成功
                finish();
            } else if (Constants.PAY_WX_FAILD.equals(type)) {//微信支付失败

            }
        }

    }

    public void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    } else if (s.length() - 1 - s.toString().indexOf(".") == 2) {
                        if (s.toString().endsWith("0") && s.toString().startsWith("0.") && String.valueOf(s.toString().charAt(2)).equals("0") && String.valueOf(s.toString().charAt(3)).equals("0")) {
                            GetToast.useString(MyScannerPayActivity.this, "输入金额不能为0元");
                            s = s.toString().subSequence(0,
                                    s.toString().indexOf(".") + 2);
                            editText.setText(s);
                            editText.setSelection(s.length());
                        }
                    } else if (s.length() - 1 - s.toString().indexOf(".") == 1) {
                        String ss1 = String.valueOf(s.toString().charAt(0));
                        String ss2 = String.valueOf(s.toString().charAt(1));
                        String ss3 = String.valueOf(s.toString().charAt(2));
                        if (s.toString().startsWith("0.") && String.valueOf(s.toString().charAt(1)).equals(".") && String.valueOf(s.toString().charAt(2)).equals(".")) {
                            s = s.toString().subSequence(0,
                                    s.toString().indexOf(".") + 1);
                            editText.setText(s);
                            editText.setSelection(s.length());
                        }
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 7) {
                    s.delete(7, s.length());
                    editText.setText(s);
                    GetToast.useString(MyScannerPayActivity.this, "最多只能输入7位数字");
                    //设定光标位置
                    editText.setSelection(s.length());
                }
            }
        });

    }
}
